<template>
  <div>
    <el-card v-if="openplugin==0" class="product-enhancer-card">
      <div slot="header" class="clearfix">
        <span>商品分销插件说明</span>
      </div>
      <div>
        当您开启商品分销插件时，将自动开启当前活动关联商品的分销配置服务，即用户参与分销活动，购买活动商品时，将赠送配置的积分、提货券、积分转化卡、现金、优惠券等给邀请人（直推和间推）与被邀请人
      </div>
      <div style="margin-top: 50px; text-align: center">
        <el-button style="width: 180px" @click="opencard" type="primary"
          >开启</el-button
        >
      </div>
    </el-card>
    <div v-else class="content">
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <el-button
            icon="el-icon-circle-plus-outline"
            @click="goodsadd"
            type="primary"
            >添加商品</el-button
          >
          <el-button icon="el-icon-setting" @click="addallocationall" type="primary"
            >批量配置</el-button
          >
        </el-col>
        <el-col :span="4" :offset="16">
          <el-button @click="subaddsunh" type="warning">关闭插件</el-button>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <el-form
            ref="allocationform"
            :model="formData"
            :rules="formRules"
            inline
          >
            <el-table
              :header-cell-style="{
                'background-color': '#f3f8fe',
                color: '#606266',
                height: '50px',
              }"
              ref="drawertable"
              v-loading="loading"
              :data="formData.check"
              @selection-change="handleSelectionChange"
              style="width: 100%"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="商品名称" align="center">
                <template slot-scope="scope">
                  <el-tooltip
                    placement="top-start"
                    :content="scope.row.goods_name + ''"
                  >
                    <div class="one_line_hidden">
                      {{ scope.row.goods_name ? scope.row.goods_name : "-" }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column align="center" prop="sort" label="商品分类">
                <template slot-scope="{ row }">
                  <span size="mini" v-if="row.category_name1">{{
                    row.category_name1
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column label="商品图片" align="center" width="80">
                <template slot-scope="scope">
                  <el-image style="width: 40px" :src="scope.row.main_image" />
                </template>
              </el-table-column>

              <el-table-column label="所属店铺" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.mer_name }}</span>
                </template>
              </el-table-column>

              <el-table-column label="商品价格" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.retail_price }}</span>
                </template>
              </el-table-column>

              <el-table-column label="奖励规则" align="center" width="200">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.award_type`"
                    :rules="formRules.nonempty"
                  >
                    <el-select
                      v-model="scope.row.award_type"
                      placeholder="请选择"
                    >
                      <el-option
                        label="按支付金额发放"
                        :value="1"
                      ></el-option>
                      <el-option
                        label="按商品利润发放"
                        :value="2"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="奖励类型" align="center" width="140">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.level`"
                    :rules="formRules.nonempty"
                  >
                  <el-select v-model="scope.row.level" placeholder="请选择">
                    <el-option label="直推" :value="1"> </el-option>
                    <el-option label="直推+间推" :value="2"> </el-option>
                  </el-select>

                </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="发放时间" align="center" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.node_day`"
                    :rules="formRules.timeFieldName"
                  >
                    <el-input v-model="scope.row.node_day" placeholder="请输入">
                      <template slot="prepend">T+</template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="时间节点" align="center" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.node_type`"
                    :rules="formRules.nonempty"
                  >
                    <el-select
                      v-model="scope.row.node_type"
                      placeholder="请选择"
                    >
                      <el-option label="支付成功" :value="1"></el-option>
                      <el-option label="确认收货" :value="2"></el-option>
                      <el-option label="评价" :value="3"></el-option>
                      <el-option label="过售后期" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>


              <el-table-column label="规则配置" align="center" width="170">
                <template slot-scope="scope">
                  <span>有{{ scope.row.goods_rule.length }}条规则</span>
                  <el-button @click="addallocation(scope.row.goods_rule,scope.row.id)" type="text">设置</el-button>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" width="110">
                <template slot-scope="scope">
                  <el-button
                  v-if="formData.check.length==1?false:true"
                    @click="goodsremove(scope.row.id)"
                    size="mini"
                    type="danger"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <!-- 配置 -->
    <allocation v-if="showallocation" :alldata="alldata" @addsutaddpro = "addsutaddpro" @childtoparent="getaddonedata" ></allocation>
    <!-- 添加商品 -->
    <addproduct
      ref="addproduct"
      v-if="ifShowadd"
      :goodsIds="ADDgoods"
      :shappingid="shappingid"
    ></addproduct>
  </div>
</template>

  <script>
import addproduct from "./components/addremovev2.vue";
import allocation from "./components/allocation.vue";

import { listfenxiao } from "@/api/index";

export default {
  props: ["shapdata", "shappingid","openplugin_retail","editdata"],
  components: {
    addproduct,
    allocation,
  },
  data() {
    return {
      editid:'',
      editids:[],
      openplugin:0,
      editfordata:'',
      loading: true,
      alldata: '',
      showallocation: false,
      ifShowadd: false,
      goodsIds: [], //选择的商品
      removeids: [], //移除的商品
      ADDgoods: [], //添加的商品
      productConfigTitle: "配置奖池商品",
      addproductTitle: "添加商品",
      showcard: true,
      multipleSelection: [],
      formData: {
        check: [],
      },
      formRules: {
        timeFieldName: [
          {
            required: false,
            validator: (rule, value, callback) => {
              let req = /^(0|[1-9]|1[0-9]|20)$/;
              if (req.test(value)) {
                callback();
              } else {
                callback(new Error("请输入0-20正整数"));
              }
            },
            trigger: "change",
          },
        ],
        moneynumber: [
          {
            required: false,
            validator: (rule, value, callback) => {
              let req = /^\d+(\.\d{1,2})?%?$/;
              let regex = /%/;
              if (regex.test(value)) {
                let jsx = /^\d+(\.\d{1,2})?%?$/;
                if (jsx.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多两位正小数"));
                }
              } else {
                if (req.test(value)) {
                  if (Number(value) > 999999) {
                    return callback(new Error("金额不能大于999999"));
                  }
                  callback();
                } else {
                  callback(new Error("保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        nonempty: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
      eventsForm: {
        activity_id: "",
        activity_type: 5,
        goods_id: [],
      },
    };
  },

  watch: {
    // 监听 shapdata 的变化
    shapdata: {
      handler(newValue, oldValue) {
        this.isshow = newValue
        this.ADDgoods = newValue;
         this.contrast(newValue)
      },
      deep: false,
    },
    editdata:{
        handler(newValue, oldValue) {
          this.editfordata = newValue;
        this.getperopdata()
        },
        deep: true,
      },
    "formData.check": {
      handler(newValue, oldValue) {
        this.$emit("updateCheckDatav2", newValue);
      },
      deep: true,
    },
    openplugin_retail:{
      handler(newValue, oldValue) {
        this.openplugin = newValue;
        this.$emit("isitenabled",newValue);
      },
      deep: true,
    }
  },

  mounted() {

  },
  methods: {

    // 现在列表对比规则列表
    contrast(val){
      if(this.editdata.is_open) {
        this.goodsIds  = this.goodsIds.filter(id => val.includes(id));
        this.getGoodsList()
      }else{
        this.goodsIds  = this.goodsIds.filter(id => val.includes(id));
        this.getGoodsList()
        let result =this.ADDgoods.filter(id => !this.goodsIds.includes(id));
        this.ADDgoods = result
      }
    },

     // 获取修改的值
     getperopdata(val) {
      this.editfordata.goods_list.forEach((item) => {
        this.goodsIds.push(item.goods_id);
      });
      this.getGoodsList();

    },




    // 获取列表
    getGoodsList() {
      this.eventsForm.goods_id = this.goodsIds;
      this.eventsForm.activity_id = this.shappingid;
      listfenxiao(this.eventsForm).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          return this.$messages.error(res.msg);
        }
        this.formData.check = res.data;

        this.formData.check.forEach((item) => {
            const defaults = {
              award_type: 1,
              node_day: 0,
              node_type: 1,
              level: 1,
            };

            Object.keys(defaults).forEach((key) => {
              if (item[key] === "") {
                item[key] = defaults[key];
              }
            });
          })
          console.log( this.formData.check)


        this.loading = false;
      });
    },
    //打开配置
    addallocation(row,ids) {
      this.showallocation = true;
      this.editid = ids;
      this.alldata = row;
    },
    // 批量配置
    addallocationall(){
      if(this.multipleSelection.length <= 0){
        this.$messages.warning('请选择商品')
      }else{
        this.showallocation = true;
        // this.editids
      }
    },
    addsutaddpro(data){
      this.multipleSelection.forEach((item) => {
        item.award_type =  data.award_type
        item.node_day =   data.node_day
        item.node_type =  data.node_type
        item.level =  data.level
        item.goods_rule =  data.goods_rule
      })
      this.toggleSelection()
    },
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.drawertable.toggleRowSelection(row);
          });
        } else {
          this.$refs.drawertable.clearSelection();
        }
      },

    //获取单个配置的数据
    getaddonedata(row){
      this.formData.check.forEach((item) => {
        if(item.id ==  this.editid){
         item.goods_rule = row
        }
      })
    },
    //删除商品
    goodsremove(idToRemove) {
      const filteredArray = this.formData.check.filter(
        (obj) => obj.id !== idToRemove
      );
      const filteredGoodsIds = this.goodsIds.filter((id) => id !== idToRemove);
      this.goodsIds = filteredGoodsIds;
      this.formData.check = filteredArray;
      this.ADDgoods.push(idToRemove);

    },
    //添加商品弹窗关闭
    closeaddproduct() {
      this.alldata = ''
      this.ifShowadd = false;
      this.showallocation = false;
      this.toggleSelection()
    },
    //拿到添加商品的回调
    addproductWay(row) {
      row.forEach((item) => {
        this.formData.check.push(item);
      });
      row.forEach((item) => {
        this.goodsIds.push(item.id);
        this.ADDgoods = this.ADDgoods.filter((removeId) => {
          return !row.some((rowItem) => rowItem.id === removeId);
        });
      });
      this.getGoodsList();
      this.$message({
        message: "添加成功",
        type: "success",
      });
    },
    addproductRowWay(row) {
      // this.goodsIds = [...this.goodsIds, ...row];
    },
    //添加商品弹窗打开
    goodsadd() {
      this.ifShowadd = true;
      let result =this.ADDgoods.filter(id => !this.goodsIds.includes(id));
      this.ADDgoods = result
    },
    subaddsunh() {
      this.openplugin = 0;
      this.$emit("isitenabled",0);
    },

    // 选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 开启
    opencard() {
      if (this.ADDgoods.length > 0 || this.editdata.is_open == 1) {
        this.openplugin = 1;
        this.$emit("isitenabled",1);
      } else {
        this.$emit("child-event", "third");
        this.$message({
          message: "请先选择指定商品",
        });
      }
    },
    // 列表分页
    handleSizeChange(val) {
      this.searchForm.count = val;
      //   this.getListWay()
    },
    // 列表分页
    handleCurrentChange(val) {
      this.searchForm.page = val;
      //   this.getListWay()
    },
  },
};
</script>

  <style>
.el-card__header {
  padding: 0;
}
</style>

  <style scoped>
.content {
  padding: 20px;
}

.product-enhancer-card {
  width: 100%;
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.product-enhancer-card .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 20px;
}
</style>
